<template>
  <div class="role-management">
    <!-- 搜索区域 -->
    <el-form :inline="true" class="form-area">
      <el-form-item label="角色名称">
        <el-input placeholder="请输入角色名称" />
      </el-form-item>
      <el-form-item label="状态">
        <el-select placeholder="请选择状态">
          <el-option label="启用" value="enable" />
          <el-option label="停用" value="disable" />
        </el-select>
      </el-form-item>
      <el-button type="primary">搜索</el-button>
    </el-form>

    <!-- 功能按钮 -->
    <div class="btn-area">
      <el-button type="primary">添加</el-button>
      <el-button type="danger">删除</el-button>
    </div>

    <!-- 表格区域 -->
    <el-table :data="roleFrom" border style="width: 100%;margin-bottom: 30px;">
      <el-table-column type="selection" width="55" />
      <el-table-column type="index" label="序号" width="80" />
      <el-table-column prop="role_Name" label="角色名称" />
      <el-table-column prop="role_Key" label="角色编码" />
      <el-table-column prop="status" label="状态">
        <template #default="scope">
          <span v-if="scope.row.status">启动</span>
          <span v-else>停用</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200">
        <template #default="scope">
          <el-button type="text" size="small">编辑</el-button>
          <el-button type="text" size="small">查看</el-button>
          <el-button type="text" size="small">删除</el-button>
          <el-button type="text" size="small"
            @click="openPermissionDialog(scope.row.role_Id, scope.row.role_Name)">分配权限</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页区域 -->
    <el-pagination layout="total, sizes, prev, pager, next" />

    <!-- 权限对话框 -->
    <el-dialog v-model="logic.isNo" center draggable title="分配权限" width="500">
      <!-- 树形组件：用于展示权限树 -->
      <el-tree ref="treeRef" style="max-width: 600px" :props="treeProps" :data="treeData" node-key="id" show-checkbox />
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="logic.isNo = false">关闭</el-button>
          <el-button type="primary" @click="savePermission">保存</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { nextTick, onMounted, reactive, ref } from 'vue'
import type { RoleResult, MenuItem, MenuResult, GetMenuseTimeate } from '@/api/type'
import { GetRole, GetMenu, GetestimateMenu, AddPermission } from '@/api/Index'
import type Node from 'element-plus/es/components/tree/src/model/node'
import { ElMessage } from 'element-plus'
import { useCounterStore } from "@/stores/counter"

const store = useCounterStore()

// 逻辑状态
const logic = reactive({
  isNo: false, // 控制对话框显示
  currentRoleId: null as number | null, // 当前角色 ID
  selectedKeys: [] as number[], // 选中的权限节点 ID
})

// 树形组件引用
const treeRef = ref()

// 权限树数据
const treeData = ref<MenuItem[]>([])

// 树形组件配置
const treeProps = {
  label: 'menuName', // 节点显示的名称字段
  children: 'children', // 子节点的字段
  isLeaf: (data: MenuItem) => {
    // 判断是否为叶子节点：无子节点或子节点为空数组
    return !data.children || data.children.length === 0
  },
}

// 打开权限分配对话框
const openPermissionDialog = async (roleId: number, roleName: string) => {
  try {
    // 1. 设置当前角色信息
    logic.currentRoleId = roleId
    logic.isNo = true

    // 2. 加载权限树数据
    const result: MenuResult = await GetMenu()
    treeData.value = result.data

    // 3. 获取当前角色已分配的权限
    const estimateResult: GetMenuseTimeate = await GetestimateMenu({
      role_Name: roleName,
    })

    // 4. 提取所有权限ID（包括嵌套子节点）
    const flattenMenuIds = (menus: MenuItem[]): number[] => {
      return menus.reduce((acc: number[], menu) => {
        acc.push(menu.id)
        if (menu.children && menu.children.length > 0) {
          acc.push(...flattenMenuIds(menu.children))
        }
        return acc
      }, [])
    }

    const checkedKeys = flattenMenuIds(estimateResult.data)

    // 5. 等待树组件渲染完成
    nextTick(() => {
      if (treeRef.value) {
        // 设置默认选中项
        treeRef.value.setCheckedKeys(checkedKeys)
      }
    })
  } catch (error) {
    console.error('获取权限失败:', error)
    ElMessage.error('权限信息获取失败')
  }
}

// 保存权限
const savePermission = async () => {
  if (!treeRef.value) return

  // 1. 获取选中的节点 ID
  const checkedKeys = treeRef.value.getCheckedKeys()
  logic.selectedKeys = checkedKeys as number[]

  // 2. 调用接口保存权限
  const Permissionadd = {
    role_Id: logic.currentRoleId,
    menu_Id: checkedKeys,
  }
  const res = await AddPermission(Permissionadd)

  // 3. 提示保存成功
  ElMessage.success('权限分配成功')
  logic.isNo = false // 关闭对话框
}

// 角色表格数据
const roleFrom = ref<RoleResult['data']>([])

// 加载角色列表数据
const roleList = async () => {
  const result: RoleResult = await GetRole()
  roleFrom.value = result.data
}

// 组件挂载时加载角色列表
onMounted(() => {
  roleList()
})
</script>

<style scoped>
.role-management {
  padding: 20px;
}

.form-area {
  display: flex;
  margin-bottom: 20px;
}

.btn-area {
  margin: 20px 0;
}

/* 添加树形容器高度限制和滚动条 */
.el-tree {
  max-height: 60vh;
  overflow-y: auto;
}
</style>